<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GPT Beat</title>
    <link rel="stylesheet" href="index.css">
    <style>
        body::after {
            content: "Beat";
            position: fixed;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            z-index: -1;
            opacity: 0.1;
            font-size: 120px;
            color: #409EFF;
            transform: rotate(-30deg);
            pointer-events: none;
            display: flex;
            justify-content: center;
            align-items: center;
            font-family: 'Arial', sans-serif;
            font-weight: bold;
        }

        #myModal {
            display: none;
            position: fixed;
            z-index: 2000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }

        .modal-content {
            background-color: white;
            margin: 15% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
            max-width: 600px;
            border-radius: 8px;
        }

        .main-container {
            min-height: 100vh;
            padding: 20px;
            background: rgba(255,255,255,0.9);
        }

        .chat-card {
            width: 90%;
            max-width: 800px;
            margin: 0 auto;
            border-radius: 12px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }

        .response-box {
            height: 60vh;
            padding: 20px;
            overflow-y: auto;
            background: #fafafa;
            border-radius: 8px;
            text-align: left;
        }

        .user-question {
            text-align: right;
            margin: 10px 0;
            padding: 8px 12px;
            background: #ecf5ff;
            border-radius: 4px;
            display: inline-block;
        }

        .assistant-response {
            margin: 10px 0;
            padding: 8px 12px;
            background: #fef0f0;
            border-radius: 4px;
            text-align: right;
        }

        .voice-indicator {
            position: fixed;
            bottom: 100px;
            left: 50%;
            transform: translateX(-50%);
            color: #67C23A;
            font-size: 14px;
        }
        .duration {
            font-size: 0.9em;
            color: #888;
        }
    </style>
</head>

<body>
    <div id="app">
        <el-container class="main-container">
            <el-card class="chat-card">
                <div slot="header" class="clearfix">
                    <span style="font-size: 18px; color: #409EFF;">
                        <i class="el-icon-cpu"></i>
                        基于DeepSeek-r1:8b与PLC GPT Beat版
                    </span>
                </div>

                <el-scrollbar class="response-box">
                    <div id="response">
                        <div v-for="(msg, index) in messages" :key="index">
<!--                            <div class="user-question" v-if="msg.role === 'user'">-->
<!--                                {{ msg.content }}-->
<!--                            </div>-->
                            <div class="user-question" v-if="msg.role === 'user'">
                             {{ cleanContent(msg.content) }}
                            </div>
                            <div class="assistant-response" v-else>
                                <div v-html="msg.content"></div>
                                <div class="duration">{{ msg.duration }}</div>
                            </div>
                        </div>
                    </div>
                </el-scrollbar>

                <div class="input-footer" style="margin-top: 2%">
                    <el-input
                        v-model="userInput"
                        placeholder="请输入问题或使用语音输入"
                        clearable
                        @keyup.enter.native="sendMessage"
                        class="input-with-button">
                        <el-button-group slot="append">
                            <el-button
                                type="primary"
                                icon="el-icon-position"
                                @click="sendMessage"
                                :loading="sending">
                                发送
                            </el-button>
                            <el-button
                                type="success"
                                icon="el-icon-microphone"
                                @click="toggleVoiceRecognition"
                                :loading="recording">
                                语音
                            </el-button>
                        </el-button-group>
                    </el-input>
                </div>
            </el-card>
        </el-container>

        <div class="voice-indicator" v-show="recording">
            <i class="el-icon-loading"></i>
            正在录音中...
        </div>

        <div id="myModal" class="modal">
            <div class="modal-content">
                <span class="el-icon-close" style="float: right; cursor: pointer;" @click="closeModal"></span>
                <h3 style="color: #409EFF; margin-bottom: 15px;">
                    <i class="el-icon-info"></i>
                    AI模型：DeepSeek-r1:8b
                </h3>
                <el-divider></el-divider>
                <p style="line-height: 1.8;">
                    <el-tag type="success" size="mini">示例指令</el-tag><br><br>
                    <el-row :gutter="10">
                        <el-col :span="24" v-for="(example, index) in examples" :key="index">
                            <el-card shadow="hover" style="margin-bottom: 10px;">
                                {{ example }}
                            </el-card>
                        </el-col>
                    </el-row>
                </p>
            </div>
        </div>
    </div>

    <script src="https://unpkg.com/vue@2.6.14/dist/vue.js"></script>
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script>

        new Vue({
            el: '#app',
            data: {
                userInput: '',
                sending: false,
                recording: false,
                messages: [],
                recognition: null,
                currentUtterance: null,
                examples: [
                    "请将A301温度调整到23℃",
                    "修改A302的工作模式为休眠模式",
                    "先设置A302压力为3MPa，然后切换A301至生产模式"
                ]
            },
            mounted() {
                this.initSpeechRecognition();
                this.showModal();
                window.speechSynthesis.onvoiceschanged = this.initVoices;
            },
            methods: {
                 cleanContent(content) {
                    if (Array.isArray(content)) {
                      return content.join(' ');
                    }
                    return String(content).replace(/[\[\]"]+/g, '');
                  },
                initSpeechRecognition() {
                    if ('webkitSpeechRecognition' in window) {
                        this.recognition = new webkitSpeechRecognition();
                        this.recognition.continuous = false;
                        this.recognition.interimResults = true;
                        this.recognition.lang = 'zh-CN';

                        this.recognition.onresult = (event) => {
                            const transcript = event.results[0][0].transcript;
                            this.userInput = transcript.trim();
                        };

                        this.recognition.onerror = (event) => {
                            console.error('识别错误:', event.error);
                            this.recording = false;
                        };

                        this.recognition.onend = () => {
                            this.recording = false;
                        };
                    }
                },

                toggleVoiceRecognition() {
                    if (!this.recording) {
                        this.recognition.start();
                        this.recording = true;
                    } else {
                        this.recognition.stop();
                        this.recording = false;
                    }
                },

                async sendMessage() {
                    if (!this.userInput.trim()) return;

                    const startTime = Date.now();
                    this.sending = true;

                    // 添加用户消息
                    this.messages.push({
                        role: 'user',
                        content: this.userInput
                    });

                    try {
                        const response = await fetch('http://localhost:8080/chat', {
                            method: 'POST',
                            headers: {'Content-Type': 'application/json'},
                            body: JSON.stringify({ message: this.userInput })
                        });

                        if (!response.ok) throw new Error(`HTTP错误 ${response.status}`);

                        const data = await response.json();
                        const duration = ((Date.now() - startTime)/1000).toFixed(2);

                        // 添加助手消息
                        this.messages.push({
                            role: 'assistant',
                            content: data.results,
                            duration: `响应时间: ${duration}秒`
                        });

                        this.speak(data.results);
                    } catch (error) {
                        this.$message.error(`请求失败: ${error.message}`);
                    } finally {
                        this.sending = false;
                        this.userInput = '';
                    }
                },

                initVoices() {
                    const voices = speechSynthesis.getVoices();
                    this.selectedVoice = voices.find(v => v.lang === 'zh-CN');
                },

                speak(text) {
                    if (this.currentUtterance) {
                        speechSynthesis.cancel();
                    }
                    this.currentUtterance = new SpeechSynthesisUtterance(text);
                    this.currentUtterance.voice = this.selectedVoice;
                    this.currentUtterance.lang = 'zh-CN';
                    speechSynthesis.speak(this.currentUtterance);
                },

                showModal() {
                    document.getElementById('myModal').style.display = 'block';
                },

                closeModal() {
                    document.getElementById('myModal').style.display = 'none';
                }
            }
        })
    </script>
</body>
</html>